package org.jeecg.modules.client;

import com.alibaba.fastjson.util.TypeUtils;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.AttributeKey;
import org.jeecg.modules.c.entity.MSC;
import org.jeecg.modules.c.service.IMSCService;
import org.jeecg.modules.hand.NettyClientHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

import static org.jeecg.modules.client.ChannelManager.SCID;

/**
 * 创建客户端实例，并向服务端发送消息
 */
@Component
public class NettyClient {

    @Autowired
    private  ChannelManager channelManager ;
    private  static ChannelManager stacicChannelManager ;

    public void  init(){
        if(stacicChannelManager==null){
            stacicChannelManager = channelManager;
        }
    }

    /**
     * 程序启动时直接连接服务端
     */
    public  static void start(MSC msc) {

        // 创建客户端线程组，用于处理io操作
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //创建bootstrap实例，启动客户端对象
        Bootstrap bootstrap = new Bootstrap();
        //将客户端线程组暂存到bootstrap中
        bootstrap.group(bossGroup);
        //设置客户端通道类型为NioSocketChannel
        bootstrap.channel(NioSocketChannel.class);
        //设置客户端处理器，用于处理客户端的请求
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                ChannelPipeline pipeline = socketChannel.pipeline();
                //获取管道对象，并添加管道处理器
                pipeline.addLast(new NettyClientHandler());
            }
        });
        //向服务端发起连接请求
        try {
            ChannelFuture localhost = bootstrap.connect(msc.getSchost(), TypeUtils.castToInt(msc.getScport())).sync();
            ChannelManager.registerChannel(msc.getScid(), localhost.channel());
            //在管道中加入自定义属性
            localhost.channel().attr(SCID).set(msc.getScid());
            localhost.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //关闭boss线程组
            bossGroup.shutdownGracefully();
        }
    }

}
